<?php

use App\Library\Registry;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\CliDumper;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;

if (!function_exists('d')) {
    /**
     * 输出信息且不退出
     */
    function d()
    {
        array_map(function ($x) {
            dump($x);
        }, func_get_args());
    }
}

if (!function_exists('dump')) {
    /**
     * 输出信息
     *
     * @param $message
     */
    function dump($message)
    {
        if (class_exists(CliDumper::class)) {
            $dumper = 'cli' === PHP_SAPI ? new CliDumper : new HtmlDumper;
            $dumper->dump((new VarCloner)->cloneVar($message));
        } else {
            var_dump($message);
        }
    }
}

if (!function_exists('get_client_ip')) {
    /**
     * 获取客户端IP
     *
     * @return array|false|mixed|string
     */
    function get_client_ip()
    {
        if ($_SERVER) {
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
                return $_SERVER["HTTP_X_FORWARDED_FOR"] ?? '';
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                return $_SERVER["HTTP_CLIENT_IP"] ?? '';
            } else if (isset($_SERVER["REMOTE_ADDR"])) {
                return $_SERVER["REMOTE_ADDR"] ?? '';
            } else {
                return 'Error';
            }
        } else {
            if (getenv('HTTP_X_FORWARDED_FOR')) {
                return getenv('HTTP_X_FORWARDED_FOR') ?? '';
            } else if (getenv('HTTP_CLIENT_IP')) {
                return getenv('HTTP_CLIENT_IP') ?? '';
            } else if (getenv('REMOTE_ADDR')) {
                return getenv('REMOTE_ADDR') ?? '';
            } else {
                return 'Error';
            }
        }
    }
}

if (!function_exists('register')) {
    /**
     * 注册全局变量
     *
     * @param $key
     * @param $value
     * @param false $force
     */
    function register($key, $value, $force = false)
    {
        Registry::set($key, $value, $force);
    }
}

if (!function_exists('registry')) {
    /**
     * 获取全局变量
     *
     * @param $key
     * @param null $default
     * @return mixed|null
     */
    function registry($key, $default = null)
    {
        return Registry::get($key, $default);
    }
}

if (!function_exists('to_sql')) {
    /**
     * 获取 builder 的sql执行语句
     *
     * @param $builder \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder
     */
    function to_sql($builder)
    {
        $sql = $builder->toSql();
        foreach ($builder->getBindings() as $binding) {
            $value = is_numeric($binding) ? $binding : "'" . $binding . "'";
            $sql = preg_replace('/\?/', $value, $sql, 1);
        }
        return $sql;
    }
}

if (!function_exists('create_dir')) {
    /**
     * 创建文件夹
     *
     * @param $filePath
     * @return bool|void
     */
    function create_dir($filePath)
    {
        $directory = dirname($filePath);
        if (is_dir($directory)) {
            return true;
        }
        if (create_dir($directory)) {
            mkdir($directory, 0777);
            return true;
        }
    }
}

if (!function_exists('verify_telephone')) {
    /**
     * 验证手机号码是否正确
     *
     * @param $telephone
     * @return bool
     */
    function verify_telephone($telephone): bool
    {
        return (bool)preg_match("/^1\d{10}$/i", $telephone);
    }
}

if (!function_exists('verify_email')) {
    /**
     * 验证邮箱格式是否正确
     *
     * @param $email
     * @return bool
     */
    function verify_email($email): bool
    {
        return (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
    }
}

if (!function_exists('second_2_diff')) {
    function second_2_diff(int $seconds): string
    {
        $year = $day = $hour = $minute = $second = 0;
        if ($seconds >= 31556926) {
            $year = floor($seconds / 31556926);
            $seconds = $seconds % 31556926;
        }
        if ($seconds >= 86400) {
            $day = floor($seconds / 86400);
            $seconds = $seconds % 86400;
        }
        if ($seconds >= 3600) {
            $hour = floor($seconds / 3600);
            $seconds = $seconds % 3600;
        }
        if ($seconds >= 60) {
            $minute = floor($seconds / 60);
            $seconds = $seconds % 60;
        }
        $second = floor($seconds);
        if ($year) {
            return "{$year}年{$day}天{$hour}小时{$minute}分钟{$seconds}秒";
        } elseif ($day) {
            return "{$day}天{$hour}小时{$minute}分钟{$seconds}秒";
        } elseif ($hour) {
            return "{$hour}小时{$minute}分钟{$seconds}秒";
        } elseif ($minute) {
            return "{$minute}分钟{$seconds}秒";
        } else {
            return "{$second}秒";
        }
    }
}

if (!function_exists('list_message')) {
    function list_message($msg = "操作成功", $success = true, $data = [], $code = 0)
    {
        if (empty($data)) {
            $data = null;
        }
        $result = ['success' => $success, 'msg' => $msg, 'data' => $data];
        if ($success) {
            $result['code'] = 0;
        } else {
            $result['code'] = $code ? $code : -1;
        }
        $recordTotal = 0;
        if (!is_array($data)) {
            $recordTotal = $data->record_total ?? 0;
            $data = $data->toArray();
        }
        if ($recordTotal) {
            $count = $recordTotal;
        } else {
            $count = $data['total'] ?? 0;
        }
        $listResult = [
            'msg' => $msg,
            'count' => $count,
            'data' => $data['data'],
            'code' => $code
        ];
        return $listResult;
    }
}

if (!function_exists('create_dir')) {
    /**
     * 创建文件夹
     *
     * @param $filePath
     * @return bool|void
     */
    function create_dir($filePath)
    {
        $directory = dirname($filePath);
        if (is_dir($directory)) {
            return true;
        }
        if (create_dir($directory)) {
            mkdir($directory, 0777);
            return true;
        }
    }
}

if (!function_exists('get_zones')) {
    /**
     * 获取省市县信息
     *
     * @param int $provinceId
     * @param int $cityId
     * @param int $countyId
     */
    function get_zones(int $provinceId, int $cityId, int $countyId)
    {
        $province = \App\Models\CityModel::find($provinceId);
        if (empty($province)) {
            $province = \App\Models\CityModel::ByCitycode($provinceId)->first();
        }
        if (empty($province)) {
            throw new Exception('省份ID错误');
        }
        $city = \App\Models\CityModel::find($cityId);
        if (empty($city)) {
            $city = \App\Models\CityModel::byCitycode($cityId)->first();
        }
        if (empty($city)) {
            throw new Exception('城市ID错误');
        }
        if ($city->pid != $province->id) {
            throw new Exception('所选城市非当前省份所属');
        }
        $county = \App\Models\CityModel::find($countyId);
        if (empty($county)) {
            $county = \App\Models\CityModel::byCitycode($countyId)->first();
        }
        if (empty($county)) {
            throw new Exception('区县ID错误');
        }
        if ($county->pid != $city->id) {
            throw new Exception('所选区县非当前城市所属');
        }

        return [
            'province_id' => $province->id,
            'province_code' => $province->citycode,
            'province_name' => $province->name,
            'city_id' => $city->id,
            'city_code' => $city->citycode,
            'city_name' => $city->name,
            'county_id' => $county->id,
            'county_code' => $county->citycode,
            'county_name' => $county->name
        ];
    }
}

if (!function_exists('service_telephone')) {
    /**
     * 获取售后电话
     * @return string
     */
    function service_telephone()
    {
        return '400-056-8166';
    }
}

if (!function_exists('is_charge')) {
    /**
     * 用户是否是区域主管
     *
     * @param $userId
     * @return bool
     */
    function is_charge($userId): bool
    {
        $userId = (int)$userId;
        if ($userId == 1) {
            return true;
        }
        $user = \App\Models\UserModel::query()
            ->join('position as p', 'p.id', '=', 'user.position_id')
            ->where('user.id', $userId)
            ->where('p.name', '=', \App\Services\DeptService::CHARGE_CODE)
            ->first();
        if (!empty($user)) {
            return true;
        }
        return false;
    }
}

if (!function_exists('is_engineer')) {
    // 是否是工程师
    function is_engineer($userId): bool
    {
        $userId = (int)$userId;
        if ($userId == 1) {
            return true;
        }
        $user = \App\Models\UserModel::query()
            ->join('position as p', 'p.id', '=', 'user.position_id')
            ->where('user.id', $userId)
            ->where('p.name', '=', \App\Services\DeptService::ENGINEER_CODE)
            ->first();
        if (!empty($user)) {
            return true;
        }
        return false;
    }
}

if (!function_exists('is_manager')) {
    /**
     * 用户是否是区域经理
     * @param $userId
     * @return bool
     */
    function is_manager($userId): bool
    {
        $userId = (int)$userId;
        if ($userId == 1) {
            return true;
        }
        $user = \App\Models\UserModel::query()
            ->join('position as p', 'p.id', '=', 'user.position_id')
            ->where('user.id', $userId)
            ->where('p.name', '=', \App\Services\DeptService::MANAGER_CODE)
            ->first();
        if (!empty($user)) {
            return true;
        }
        return false;
    }
}